package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Cart;
import com.jt.pojo.User;
import com.jt.service.DubboCartService;
import com.jt.utils.ThreadLocalUtil;
import com.jt.vo.SysResult;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author dc
 * @Classname CartController
 * @Date 2020/2/28 14:09
 */
@RequestMapping("/cart")
@Controller
public class CartController {

    @Reference(check = false,loadbalance = "roundrobin")
    private DubboCartService cartService;

    /**
     * 实现购物车页面跳转
     * http://www.jt.com/cart/show.html
     * 查询购物车信息:
     * 1.动态获取UserId
     * 2.通过jt-cart后台项目,动态获取购物车记录
     * 3.将数据展现到页面中
     * @return 购物车页面
     */
    @RequestMapping("/show")
    public String show(Model model, HttpServletRequest request){
        /**利用request域进行取值*/
        User user = (User)request.getAttribute("JT_USER");
        List<Cart> cartList = cartService.findCartListByUserId(user.getId());
        model.addAttribute("cartList",cartList);
        return "cart";
    }

    /**
     * 购物车新增
     * url:"http://www.jt.com/cart/add/${item.id}.html"
     * 参数接收: 如果参数名称和对象属性相同,则可以直接转换
     * @param cart 购物车商品
     * @return 重定到购物车展现页面
     */
    @RequestMapping("/add/{itemId}")
    public String addCart(Cart cart){
        /**利用ThreadLocal方法获取UserId*/
        Long userId = ThreadLocalUtil.getUser().getId();
        cart.setUserId(userId);
        cartService.saveCart(cart);
        return "redirect:/cart/show.html";
    }

    /**
     *
     */
    @RequestMapping("/update/num/{itemId}/{num}")
    @ResponseBody
    public SysResult updateNum(Cart cart){
        Long userId = ThreadLocalUtil.getUser().getId();
        cart.setUserId(userId);
        cartService.updateItemNum(cart);
        return SysResult.success();
    }

    /**
     * 实现购物车删除操作
     */
    @RequestMapping("/delete/{itemId}")
    public String deleteCart(Cart cart) {
        Long userId = ThreadLocalUtil.getUser().getId();
        cart.setUserId(userId);
        cartService.deleteCart(cart);
        //重定向到购物车列表页面
        return "redirect:/cart/show.html";
    }

}
